package com.amap.http.impl;

import com.amap.exception.AmapException;
import com.amap.http.HttpClientStrategy;
import com.amap.utils.BeanUtils;
import java.util.Map;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
/**
 * @author liuyi
 * @since 2025/10/31 11:12
 */
@Service
public class AmapRestTemplateHttpClient implements HttpClientStrategy {
    private final RestTemplate restTemplate = new RestTemplate();

    @Override
    public String postForm(String url, Map<String, String> params) throws AmapException {
        if (url != null && !url.isEmpty()) {
            try {
                MultiValueMap<String, Object> formData = BeanUtils.convertToMultiValueMap(params);
                HttpHeaders headers = new HttpHeaders();
                headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
                HttpEntity<MultiValueMap<String, Object>> request = new HttpEntity(formData, headers);
                ResponseEntity<String> response = this.restTemplate.postForEntity(url, request, String.class, new Object[0]);
                if (response.getStatusCode().is2xxSuccessful()) {
                    return (String)response.getBody();
                } else {
                    throw new AmapException("HTTP request failed with status: " + String.valueOf(response.getStatusCode()));
                }
            } catch (Exception e) {
                throw new AmapException("Failed to execute HTTP POST request to: " + url, e);
            }
        } else {
            throw new AmapException("URL cannot be null or empty");
        }
    }
}
